import { Button, message, RangePicker, Space } from 'ant-design-vue'
import { defineComponent, ref } from 'vue'
import { useRouter } from 'vue-router'

import { orderApi } from '@/apis'
import { type ProTableProps, type ProTableRef, ProTable } from '@/components'
import { TABLE_FORMAT, TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import { useDialog } from '@/hooks'
import { optionsToMap } from '@/utils'
import { handlePrice } from '@/utils/bsshow'

import {
  brandIdMap,
  brandIdOptions,
  couponTypeOptions,
  orderStatusMap,
  orderStatusOptions,
  orderThirdStatusMap,
  orderThirdStatusOptions,
  refundStatusOptions
} from '../constants'

export default defineComponent({
  name: 'DcOrderManage',
  setup() {
    const { showConfirm } = useDialog()
    const tableRef = ref({} as ProTableRef)
    const times = ref([] as any[])
    const tableConfig = ref({
      fixedHeight: true,
      options: {
        border: true,
        align: 'center',
        formConfig: {
          items: [
            {
              title: '商品供应商',
              field: 'brandId',
              itemRender: {
                name: TABLE_ITEM_RENDER.ASelect,
                props: {
                  placeholder: '全部'
                },
                options: brandIdOptions
              }
            },
            {
              title: '订单编号',
              field: 'orderNo',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入订单编号'
                }
              }
            },
            {
              title: '手机号',
              field: 'phone',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入手机号'
                }
              }
            },
            {
              title: '订单状态',
              field: 'status',
              itemRender: {
                name: TABLE_ITEM_RENDER.ASelect,
                props: {
                  placeholder: '请选择'
                },
                options: orderStatusOptions
              }
            },
            {
              title: '第三方状态',
              field: 'thirdStatus',
              itemRender: {
                name: TABLE_ITEM_RENDER.ASelect,
                props: {
                  placeholder: '请选择'
                },
                options: orderThirdStatusOptions
              }
            },
            {
              title: '支付时间',
              itemRender: {
                name: TABLE_RENDERER.FormItemDate,
                props: {
                  type: 'range',
                  placeholder: ['开始时间', '结束时间'],
                  valueFormat: 'x',
                  keys: ['startTime', 'endTime']
                }
              }
            },
            {
              itemRender: {
                name: TABLE_RENDERER.FormItemBtns
              }
            }
          ]
        },
        columnConfig: {
          minWidth: 100,
          resizable: true
        },
        columns: [
          {
            title: '订单编号',
            field: 'orderNo',
            minWidth: 220
          },
          {
            title: '第三方订单号',
            field: 'tradeNo',
            minWidth: 220
          },
          {
            title: '微信订单号',
            field: 'wxTransactionId',
            minWidth: 220
          },
          {
            title: '商品供应商',
            field: 'brandId',

            formatter: ({ cellValue }) => {
              return brandIdMap[cellValue]
            }
          },
          {
            title: '商品所属门店',
            field: 'restaurantName',
            minWidth: 200
          },
          {
            title: '状态',
            field: 'status',
            minWidth: 120,
            formatter: ({ cellValue }) => {
              return orderStatusMap[cellValue]
            }
          },
          {
            title: '第三方状态',
            field: 'thirdStatus',

            formatter: ({ cellValue }) => {
              return orderThirdStatusMap[cellValue]
            }
          },
          {
            title: '数量',
            field: 'purchaseQuantity',
            minWidth: 90
          },
          {
            title: '优惠券',

            slots: {
              default: 'couponInfo'
            }
          },
          {
            title: '实付金额',
            minWidth: 150,
            slots: {
              default: 'salePrice'
            }
          },
          {
            title: '下单人',
            field: 'wxNickName'
          },
          {
            title: '下单人手机号',
            field: 'phone',
            minWidth: 120
          },
          {
            title: '下单时间',
            field: 'createTime',
            minWidth: 170,
            formatter: TABLE_FORMAT.Date
          },
          {
            title: '出餐时间',
            field: 'outMealTime',
            minWidth: 170,
            formatter: TABLE_FORMAT.Date
          },
          {
            title: '操作',
            fixed: 'right',
            slots: {
              default: 'operation'
            },
            width: 150
          }
        ],
        pagerConfig: {
          pageSize: 15
        },
        proxyConfig: {
          form: true,
          props: {
            result: 'records',
            total: 'total'
          },
          ajax: {
            query: async ({ page, form }) => {
              const data = await orderApi.getOrderList({
                pageParameter: {
                  pageSize: page.pageSize,
                  currentPage: page.currentPage
                },
                startTime:
                  times.value.length > 0 ? times.value[0].format('x') : null,
                endTime:
                  times.value.length > 1 ? times.value[1].format('x') : null,
                ...form
              })
              return data
            }
          }
        }
      }
    } as ProTableProps)

    const router = useRouter()

    function handleAfterSale(row) {
      showConfirm({
        content: '是否确认售后，发起后将原路退款给到用户并生成新的售后订单？',
        onOk: async () => {
          try {
            await orderApi.orderRefund(row.orderNo)
            tableRef.value.refresh()
            message.success('操作完成')
          } catch (error) {}
        }
      })
    }

    function handleOrderDetail(row) {
      router.push({
        name: 'DcOrderDetailManage',
        query: {
          id: row.id,
          orderNo: row.orderNo,
          brandId: row.brandId,
          restaurantName: row.restaurantName,
          thirdStatus: row.thirdStatus,
          status: row.status,
          wxNickName: row.wxNickName,
          phone: row.phone,
          createTime: row.createTime,
          outMealTime: row.outMealTime,
          payTime: row.payTime,
          refundTime: row.refundTime,
          code: row.code,
          payMoneyText: handlePrice(row.realIncome, row.realGold)
        }
      })
    }

    return {
      tableRef,
      tableConfig,
      times,
      handleAfterSale,
      handleOrderDetail,
      handlePrice
    }
  },
  render() {
    return (
      <div>
        <ProTable
          ref="tableRef"
          v-slots={{
            timeSelect: () => {
              return (
                <Space>
                  <RangePicker v-model:value={this.times} />
                </Space>
              )
            },
            couponInfo: ({ row }) => {
              if (row.couponType) {
                return (
                  <Space>
                    {`${optionsToMap(couponTypeOptions)[row.couponType]} ${
                      row.discount
                    }折`}
                  </Space>
                )
              }
              return '无'
            },
            salePrice: ({ row }) => {
              return <Space>{handlePrice(row.realIncome, row.realGold)}</Space>
            },
            operation: ({ row }) => (
              <Space>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleOrderDetail(row)}
                >
                  订单详情
                </Button>
                <Button
                  type="link"
                  size="small"
                  disabled={!row.isAfterSale}
                  onClick={() => this.handleAfterSale(row)}
                >
                  售后
                </Button>
              </Space>
            )
          }}
          {...this.tableConfig}
        />
      </div>
    )
  }
})
